package com.chansos.dubbogo.util;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ResourceUtils {
    public static InputStream getResource(String path) {
        try {
            return ResourceUtils.class.getResourceAsStream(path);
        } catch (Exception ignore) {
        }
        return null;
    }

    public static void init(String path) {
        try {
            cmd(path,
                    "go",
                    new HashMap<>() {{
                        put("GO111MODULE", "on");
                    }},
                    new HashMap<>() {{
                        put("mod", "tidy");
                    }});
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (String p : listFile(new File(path))) {
            try {
                cmd(path,
                        "go",
                        new HashMap<>() {{
                            put("GO111MODULE", "on");
                        }},
                        new HashMap<>() {{
                            put("fmt", p);
                        }});
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void cmd(String path, String p, Map<String, String> env, Map<String, String> param) throws ExecutionException, InterruptedException {
        GeneralCommandLine command = new GeneralCommandLine(p);
        if (param != null) {
            env.forEach(command::withEnvironment);
        }
        if (param != null) {
            param.forEach(command::withParameters);
        }
        command.setWorkDirectory(path);
        Process process = command.createProcess();
        process.waitFor();
    }

    private static List<String> listFile(File root) {
        if (root == null || !root.exists()) {
            return null;
        }
        if (root.isFile() && root.getAbsolutePath().endsWith(".go")) {
            return new ArrayList<>() {{
                add(root.getAbsolutePath());
            }};
        }
        List<String> list = new ArrayList<>();
        File[] files = root.listFiles();
        if (files == null) {
            return null;
        }
        for (File file : files) {
            List<String> r = listFile(file);
            if (r != null) {
                list.addAll(r);
            }
        }
        return list;
    }
}
